package com.eightbears.beboy.ui.user.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;

import com.eightbears.beboy.R;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.cache.DistrictCache;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.picker.AddressPickTask;
import com.eightbears.beboy.base.view.picker.entity.City;
import com.eightbears.beboy.base.view.picker.entity.County;
import com.eightbears.beboy.base.view.picker.entity.Province;
import com.eightbears.beboy.entity.AddShoppingAddressEntity;
import com.eightbears.beboy.entity.LocationEntity;
import com.eightbears.beboy.entity.ShoppingAddressEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.greendao.District;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_ADDADDRESS;
import static com.eightbears.beboy.ui.user.activity.ShoppingAddressActivity.PARAMS_ADDRESS_INFO;

public class AddShoppingAddressActivity extends BaseActivity {

    public static final String EVENT_ADDRESS_SUCCESS = "addressUpdate";

    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_location)
    TextView tv_location;
    @BindView(R.id.et_full_text)
    EditText et_full_text;
    @BindView(R.id.et_name)
    EditText et_name;
    @BindView(R.id.et_phone)
    EditText et_phone;

    private String myAddress, districtName, cityName, provinceName; // 地址信息
    private String districtId, cityId, provinceId;
    private String name, phone, fullAddress;
    private ShoppingAddressEntity.ShoppingAddress mShoppingAddress;
    private LocationEntity mLocationEntity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_shopping_address);

        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        tv_title.setText(R.string.text_add_address);
    }

    @Override
    protected void initData() {
        mLocationEntity = SPUtil.getUserLocation();
        if(getExtras() != null) {
            mShoppingAddress = (ShoppingAddressEntity.ShoppingAddress) getExtras().get(PARAMS_ADDRESS_INFO);
        }
        initAddress();
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    private void initAddress() {
        if (null != mShoppingAddress) {
            District province = DistrictCache.getInstance(mContext).getCacheById(mShoppingAddress.getProvince_id());
            District city = DistrictCache.getInstance(mContext).getCacheById(mShoppingAddress.getCity_id());
            District district = DistrictCache.getInstance(mContext).getCacheById(mShoppingAddress.getDistrict_id());

            provinceName = province.getName();
            provinceId = province.getId();
            cityName = city.getName();
            cityId = city.getId();
            districtName = district.getName();
            districtId = district.getId();
            fullAddress = mShoppingAddress.getAddress();

            et_name.setText(mShoppingAddress.getName());
            et_phone.setText(mShoppingAddress.getMobile());
            et_full_text.setText(mShoppingAddress.getAddress());

        } else {
            if(null != mLocationEntity) {
                provinceName = mLocationEntity.getProvinceName();
                provinceId = mLocationEntity.getProvinceId();
                cityName = mLocationEntity.getCityName();
                cityId = mLocationEntity.getCityId();
                districtName = mLocationEntity.getDistrictName();
                districtId = mLocationEntity.getDistrictId();
            }

        }

        myAddress = provinceName + " " + cityName + " " + districtName;
        tv_location.setText(myAddress);
    }

    /**
     * 验证输入
     */
    private boolean validInput() {
        fullAddress = et_full_text.getText().toString().trim();
        name = et_name.getText().toString().trim();
        phone = et_phone.getText().toString().trim();

        if (TextUtils.isEmpty(name)) {
            ShowToast.showShortToast(getString(R.string.text_recipients));
            return false;
        }

        if (TextUtils.isEmpty(phone)) {
            ShowToast.showShortToast(getString(R.string.text_recipients_phone));
            return false;
        }

        if (!CommonUtils.checkTelephone(phone)) {
            ShowToast.showShortToast(getString(R.string.alert_phone_error));
            return false;
        }

        if (TextUtils.isEmpty(fullAddress)) {
            ShowToast.showShortToast(getString(R.string.text_full_address));
            return false;
        }

        if (TextUtils.isEmpty(myAddress)) {
            ShowToast.showShortToast(getString(R.string.text_district));
            return false;
        }

        return true;
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @OnClick(R.id.rl_select_location)
    void selectLocation() {
        AddressPickTask task = new AddressPickTask(this);
        task.setHideProvince(false);
        task.setHideCounty(false);
        task.setCallback(new AddressPickTask.Callback() {
            @Override
            public void onAddressPicked(Province province, City city, County county) {
                districtId = county.getAreaId();
                cityId = city.getAreaId();
                provinceId = province.getAreaId();
                myAddress = province.getAreaName() + " " + city.getAreaName() + " " + county.getAreaName();
                tv_location.setText(myAddress);
            }

            @Override
            public void onAddressInitFailed() {
                ShowToast.showShortToast(getString(R.string.error_init_data));
            }

        });
        task.execute(provinceName, cityName, districtName);
    }

    @OnClick(R.id.btn_submit)
    void submitAddress() {
        if (validInput()) {
            if (mShoppingAddress == null) {
                postAddAddress();
            } else {
                updateAddress();
            }
        }
    }

    @OnClick(R.id.iv_contact_list)
    void getContacts() {
        Uri uri = Uri.parse("content://contacts/people");
        Intent intent = new Intent(Intent.ACTION_PICK, uri);
        startActivityForResult(intent, 0);
    }


    public void postAddAddress() {
        OkHttpUtils.post().url(URL_ADDADDRESS)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("province_id", provinceId)
                .addParams("city_id", cityId)
                .addParams("district_id", districtId)
                .addParams("mobile", phone)
                .addParams("name", name)
                .addParams("address", fullAddress)
                .build().execute(new StringCallback() {
            @Override

            public void onResponse(String response) {
                AddShoppingAddressEntity addAddressEntity = GsonUtil.fromJson(response, AddShoppingAddressEntity.class);
                if (addAddressEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    EventBus.getDefault().post(EVENT_ADDRESS_SUCCESS);
                    ShowToast.showShortToast(getString(R.string.alert_submit_success));
                    finish();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                ShowToast.showShortToast(getString(R.string.text_update_head_error));
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(AddShoppingAddressActivity.this, status_error);
            }
        });
    }

    public void updateAddress() {
        OkHttpUtils.put().url(URL_ADDADDRESS + mShoppingAddress.getId())
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("province_id", provinceId)
                .addParams("city_id", cityId)
                .addParams("district_id", districtId)
                .addParams("mobile", phone)
                .addParams("name", name)
                .addParams("address", fullAddress)
                .build().execute(new StringCallback() {
            @Override

            public void onResponse(String response) {
                AddShoppingAddressEntity addAddressEntity = GsonUtil.fromJson(response, AddShoppingAddressEntity.class);
                if (addAddressEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    EventBus.getDefault().post(EVENT_ADDRESS_SUCCESS);
                    ShowToast.showShortToast(getString(R.string.alert_submit_success));
                    finish();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                ShowToast.showShortToast(getString(R.string.text_update_head_error));
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(AddShoppingAddressActivity.this, status_error);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 0:
                if (data == null) {
                    return;
                }
                //处理返回的data,获取选择的联系人信息
                Uri uri = data.getData();
                String[] contacts = getPhoneContacts(uri);
                if (contacts[0] != null) {
                    name = contacts[0];
                    et_name.setText(name);
                }

                if (contacts[1] != null){
                    phone = contacts[1].toString();
                    et_phone.setText(phone);
                } else {
                    et_phone.setText("");
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                if (phone.getCount() == 0) {
                    ShowToast.showShortToast(getString(R.string.error_select_phone));
                } else {
                    contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                }

            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

}
